//
//  BoostDelegate.m
//  FlutterHybrid
//
//  Created by yuan xiaodong on 2021/9/3.
//  Copyright © 2021 yuan. All rights reserved.
//

#import "BoostDelegate.h"

@interface BoostDelegate()

@property (nonatomic, strong) NSMutableDictionary *resultTable;

@end

@implementation BoostDelegate

- (NSMutableDictionary *)resultTable{
    if (!_resultTable){
        _resultTable = @{}.mutableCopy;
    }
    return _resultTable;
}

///如果框架发现您输入的路由表在flutter里面注册的路由表中找不到，那么就会调用此方法来push一个纯原生页面
- (void) pushNativeRoute:(NSString *) pageName arguments:(NSDictionary *) arguments{
    BOOL isPresent = [arguments[@"isPresent"] boolValue];
    BOOL isAnimated = [arguments[@"isAnimated"] boolValue];
    
    UIViewController *targetViewController = UIViewController.new;
    if (isPresent){
        [self.navigationController presentViewController:targetViewController animated:isAnimated completion:nil];
    }else{
        [self.navigationController pushViewController:targetViewController animated:isAnimated];
    }
}

///当框架的withContainer为true的时候，会调用此方法来做原生的push
- (void) pushFlutterRoute:(FlutterBoostRouteOptions *)options{
    FBFlutterViewContainer *vc = FBFlutterViewContainer.new;
    [vc setName:options.pageName uniqueId:options.uniqueId params:options.arguments opaque:options.opaque];
    
    BOOL isPresent = [options.arguments[@"isPresent"] boolValue];
    BOOL isAnimated = [options.arguments[@"isAnimated"] boolValue];
    
    self.resultTable[[vc uniqueIDString]] = options.onPageFinished;
    
    if (isPresent || !options.opaque){
        [self.navigationController presentViewController:vc animated:isAnimated completion:nil];
    }else{
        [self.navigationController pushViewController:vc animated:isAnimated];
    }
}

///当pop调用涉及到原生容器的时候，此方法将会被调用
- (void) popRoute:(FlutterBoostRouteOptions *)options{
    FBFlutterViewContainer *vc = (FBFlutterViewContainer *)self.navigationController.presentedViewController;
    if ([[vc uniqueIDString] isEqualToString:options.uniqueId]){
        //这里分为两种情况，由于UIModalPresentationOverFullScreen下，生命周期显示会有问题
        //所以需要手动调用的场景，从而使下面底部的vc调用viewAppear相关逻辑
        if (vc.modalPresentationStyle == UIModalPresentationOverFullScreen){
            [self.navigationController.topViewController beginAppearanceTransition:true animated:false];
            [vc dismissViewControllerAnimated:true completion:^{
                [self.navigationController.topViewController endAppearanceTransition];
            }];
        }else{
            [vc dismissViewControllerAnimated:true completion:nil];
        }
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    void(^onPageFinshed)(NSDictionary*) = _resultTable[options.uniqueId];
    if (onPageFinshed){
        onPageFinshed(options.arguments);
        [_resultTable removeObjectForKey:options.uniqueId];
    }
}

@end
